package com.heima.wemedia.service.impl;
/*
    
 需求描述：
 @Author: wang
 @Date: 2022/10/14 10:27
 
 */

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WeMediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutomaticCheckService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private WmMaterialService materialService;
    @Autowired
    private WmNewsTaskService newsTaskService;

    /**
     * 获取自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lqw.eq(WmNews::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            lqw.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            lqw.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lqw.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }


        lqw.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        lqw.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> page = page(new Page<>(dto.getPage(), dto.getSize()), lqw);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 自媒体文章提交（联合操作素材表和中间表和文章表）
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        // 获取内容集合
        List<Map> mapList = JSON.parseArray(dto.getContent(), Map.class);
        //获取内容图片集合
        List<Object> contentImages = mapList.stream().filter(item -> "image".equals(item.get("type"))).map(item -> item.get("value")).collect(Collectors.toList());
        //获取初始封面图片集合（自动和无图情况下为null）
        List<String> coverImages = dto.getImages();

        // 自动模式下构造图片信息集合
        if (Objects.equals(dto.getType(), WeMediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = contentImages.size();
            if (size == 0) {
                dto.setType((short) 0);
            }
            if (size >= 3) {
                for (Object s : contentImages.stream().limit(3).collect(Collectors.toList())) {
                    coverImages.add((String) s);
                }
                dto.setType(WeMediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (size > 0 && size < 3) {
                for (Object s : contentImages.stream().limit(1).collect(Collectors.toList())) {
                    coverImages.add((String) s);
                }
                dto.setType(WeMediaConstants.WM_NEWS_MANY_IMAGE);
            }

        }
        // 保存或修改文章
        WmNews wmNews = saveOrUpdateNews(dto, coverImages);

        //如果状态为0，则保存为草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //有封面图
        if (coverImages.size() > 0) {
            // 为中间表制作materialIds 对象
            saveRelativeInfoForCover(coverImages, wmNews, WeMediaConstants.WM_COVER_REFERENCE);
        }


        // 内容图
        if (contentImages.size() > 0) {
            saveRelativeInfoForCover(contentImages, wmNews, WeMediaConstants.WM_CONTENT_REFERENCE);
        }


//        // 自动审核调用
//        AutomaticCheckService.autoScanWmNews(wmNews.getId());
        newsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult viewDetails(Integer id) {
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        return ResponseResult.okResult(wmNews);
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(501, "文章id不可缺少");
        }
        WmNews news = getById(id);
        if (news == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        if (news.getStatus() == WeMediaConstants.WM_STATUS_PUBLISHED) {
            return ResponseResult.errorResult(501, "文章已发布，不能删除");
        }
        removeById(id);
        LambdaQueryWrapper<WmNewsMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNewsMaterial::getNewsId, id);
        newsMaterialMapper.delete(lqw);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 自媒体端控制文章上架下架
     *
     * @param wmNewsDto
     * @return
     */
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        WmNews wmNews = new WmNews();
        wmNews.setId(wmNewsDto.getId());
        wmNews.setEnable(wmNewsDto.getEnable());
        boolean flag = updateById(wmNews);
        if (flag){
            // 发送消息
            kafkaTemplate.send("news_enable_topic",JSON.toJSONString(wmNewsDto));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    /**
     * 保存或者修改Wmnews对象
     *
     * @param dto
     * @param coverImages
     * @return
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto, List<String> coverImages) {
        // 构造news,保存
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setTitle(dto.getTitle());
        if (coverImages.size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        // 判断是提交还是存入草稿
        if (dto.getId() == null) {
            save(wmNews);
        } else {
            //删除文章图片与素材的关系
            newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));
            updateById(wmNews);
        }
        return wmNews;
    }

    /**
     * 往文章和素材的中间表添加数据
     *
     * @param images
     * @param wmNews
     * @param type
     */
    private void saveRelativeInfoForCover(List images, WmNews wmNews, Short type) {
        images = (List) images.stream().distinct().collect(Collectors.toList());

        List<Integer> materialIds = new ArrayList<>();
        for (Object image : images) {
            LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
            if (image != null) {
                lqw.eq(WmMaterial::getUrl, image);
                materialIds.add(materialService.getOne(lqw).getId());
            }


        }
        newsMaterialMapper.saveRelations(materialIds, wmNews.getId(), type);
    }
}
